package com.dcm.pay.controller;

/**
 * @author 牛浩
 */
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.dcm.common.annotation.EnableResponseBodyAdvice;
import com.dcm.pay.config.AlipayConfig;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @author 牛浩
 */
@Api(tags = "alipay")
@RestController
@RequestMapping("/alipay")
@EnableResponseBodyAdvice
public class Alipay {

    @GetMapping("/pay")
    public void pay(HttpServletResponse response,
                    @RequestParam(value = "name",required = false) String name,
                    @RequestParam(value = "price",required = false) double price
    ) throws Exception {
        DefaultAlipayClient client = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();

        HashMap<String, Object> map = new HashMap<String, Object>(16);
        map.put("out_trade_no",System.currentTimeMillis());
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        map.put("total_amount",price+"");
        map.put("subject",name);
        String string = JSONObject.toJSONString(map);
        System.out.println(string);
        alipayTradePagePayRequest.setBizContent(string);
        String body = client.pageExecute(alipayTradePagePayRequest).getBody();


        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(body);
        response.getWriter().flush();
        response.getWriter().close();

    }
}
